<template>
  <el-dialog
    :title="!dataForm.fontCode ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="字体名" prop="fontCnName">
      <el-input v-model="dataForm.fontCnName" placeholder=""></el-input>
    </el-form-item>
    <el-form-item label="字体类型" prop="fontType">
      <el-input v-model="dataForm.fontType" placeholder="" disabled></el-input>
    </el-form-item>
      <el-form-item label="字体包" prop="fontFileUrl">
        <el-upload
          ref="fontFileUpload"
          :auto-upload=false
          class="upload-demo"
          drag
          :data="dataFileObj"
          :action="dataFileObj.host"
          :before-upload="getFilePolicy"
          :on-success="handleFontFileUploadSuccess"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传字体文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="clearData">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        makeSure: false,
        dataForm: {
          fontCode: '',
          fontCnName: '',
          fontType: 'json',
          fontFileUrl: '',
          fontImageUrl: ''
        },
        dataFileObj: {
          policy: '',
          signature: '',
          OSSAccessKeyId: '',
          key: '',
          dir: '',
          host: '',
          expire: ''
        },
        dataRule: {
          fontCnName: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          fontType: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          fontFileUrl: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ]

        }
      }
    },
    methods: {
      init (fontCode) {
        this.dataForm.fontCode = fontCode || ''
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.fontCode) {
            this.$http({
              url: this.$http.adornUrl(`/font/font/queryWormholeGalaxyFont`),
              method: 'post',
              data: this.$http.adornData({
                "fontCode":this.dataForm.fontCode,
                "fontCnName":this.dataForm.fontCnName,
                "fontType":this.dataForm.fontType,
                "fontFileUrl":this.dataForm.fontFileUrl,
              })
            }).then(({data}) => {
              if (data) {
                this.dataForm.fontCode = data.data.fontCode
                this.dataForm.fontCnName = data.data.fontCnName
                this.dataForm.fontType = data.data.fontType
                this.dataForm.fontFileUrl = data.data.fontFileUrl
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.makeSure = false;
        this.$refs.fontFileUpload.submit()
        // 使用轮询方式等待上传完成后再提交表单
        const checkUpload = setInterval(() => {
          if (this.makeSure) {
            clearInterval(checkUpload);
            this.submitFormData();
          }
        }, 100);

        // 设置超时时间，避免无限等待
        setTimeout(() => {
          clearInterval(checkUpload);
          if (!this.makeSure) {
            this.$message.warning('上传超时，请重新尝试');
          }
        }, 10000);

      },
      // 提交表单数据
      submitFormData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/font/font/${!this.dataForm.fontCode ? 'createWormholeGalaxyFont' : 'updateWormholeGalaxyFont'}`),
              method: 'post',
              data: this.$http.adornData({
                'fontCode': this.dataForm.fontCode || '',
                'fontCnName': this.dataForm.fontCnName,
                'fontType': this.dataForm.fontType,
                'fontFileUrl': this.dataForm.fontFileUrl,
              })
            }).then(({ data }) => {
              if (data && data.success) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit('refreshDataList');
                  },
                });
                this.clearData();
              } else {
                this.$message.error(data.msg);
                this.clearData();
              }
            });
          }
        });

      },

      getFilePolicy(file) {
        return this.$http({
          url: this.$http.adornUrl('/oss/uploadByPolicy'),
          method: 'post',
          data: this.$http.adornData({
            "path": 'font',
          })
        }).then(({data}) => {
          if (data) {
            this.dataFileObj.key = data.data.dir+file.name
            this.dataFileObj.policy = data.data.policy
            this.dataFileObj.signature = data.data.signature
            this.dataFileObj.OSSAccessKeyId = data.data.accessKeyId
            this.dataFileObj.dir = data.data.dir
            this.dataFileObj.host = data.data.host
            this.dataFileObj.expire = data.data.expire
          }
        })
      },
      // 字体包上传成功处理
      handleFontFileUploadSuccess(response, file, fileList) {
        this.$message.success('字体包上传成功！');
        this.dataForm.fontFileUrl = this.dataFileObj.host+"/"+this.dataFileObj.key
        this.makeSure = true
      },
      // 清除表单数据
      clearData() {
        this.dataForm.fontCnName = ''
        this.dataForm.fontType = 'json'
        this.dataForm.fontFileUrl = ''
        this.$refs.fontFileUpload && this.$refs.fontFileUpload.clearFiles()
        this.visible= false
      }
    }
  }
</script>

<style scoped>
.upload-demo {
  width: 100%;
}

.upload-demo ::v-deep .el-upload {
  width: 100%;
}

.upload-demo ::v-deep .el-upload-dragger {
  width: 100%;
}
</style>
